package com.surekam.mnai.service.extractor;

import java.util.HashSet;
import java.util.Set;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.surekam.mnai.model.MobileNumberAttribution;
import com.surekam.mnai.service.extractor.parser.ParseFailedException;

/**
 * 抓取器集合。
 * 
 * @author 吴政
 * 
 */
@Component
@Transactional
public class MobileNumberAttributionExtractors implements
		IMobileNumberAttributionExtractor {

	/**
	 * 抓取器集。
	 */
	private Set<IMobileNumberAttributionExtractor> extractorSet;

	/**
	 * 使用抓取器集抓取数据。如果不存在一个抓取器能返回正确结果，则抛出最后一个进行抓取的抓取器抛出的异常。
	 * 
	 * @see com.surekam.mnai.service.extractor.IMobileNumberAttributionExtractor#extract(java.lang.String)
	 */
	@Override
	public MobileNumberAttribution extract(String mobileNumber)
			throws OutOfLimitationException, ConnectionFailedException,
			ParseFailedException {
		String exceptionMsg = "";
		
		for (IMobileNumberAttributionExtractor extractor : extractorSet) {
			try {
				return extractor.extract(mobileNumber);
			} catch (Exception e) {
			}
		}
		
		throw new ParseFailedException(exceptionMsg);
	}

	public void addExtractor(IMobileNumberAttributionExtractor extractor) {
		extractorSet.add(extractor);
	}

	public void removeExtractor(IMobileNumberAttributionExtractor extractor) {
		extractorSet.remove(extractor);
	}

	public Set<IMobileNumberAttributionExtractor> getExtractorSet() {
		Set<IMobileNumberAttributionExtractor> clone = new HashSet<IMobileNumberAttributionExtractor>();
		clone.addAll(extractorSet);

		return clone;
	}

	public void setExtractorSet(
			Set<IMobileNumberAttributionExtractor> extractorSet) {
		this.extractorSet = extractorSet;
	}

}
